package xin.mydreams.mybill.global.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 支持跨域和防盗链
 *
 * @Type MyCorsFilter.java
 * @Desc
 * @mail guzehao@mydreams.xin
 * @author 谷泽昊
 * @date 2019年5月27日 下午10:15:06
 * @version
 */
@Component
public class MyCorsFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
        String origin = request.getHeader("Origin");
        System.err.println(origin);
        response.setHeader("Access-Control-Allow-Origin", origin);
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		String method = request.getMethod();
		if(method.equalsIgnoreCase("OPTIONS")){
			res.getOutputStream().write("Success".getBytes("utf-8"));
		}else{
			chain.doFilter(req, res);
		}



	}

	@Override
	public void init(FilterConfig filterConfig) {
	}

	@Override
	public void destroy() {
	}

}
